<!--周建威-->
<!--2017/10/19-->
<template>
    <section>
        <!--搜索start -->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters"  @submit.native.prevent>
                <el-form-item label="品牌名称">
                    <el-input v-model.trim="filters.brand_name" placeholder="品牌名"></el-input>
                </el-form-item>
                <!--<el-form-item label="首字母">-->
                    <!--<template>-->
                        <!--<el-select v-model="filters.brand_initial" placeholder="请选择">-->
                            <!--<el-option-->
                                    <!--v-for="item in letterOption"-->
                                    <!--:key="item.value"-->
                                    <!--:label="item.label"-->
                                    <!--:value="item.value">-->
                            <!--</el-option>-->
                        <!--</el-select>-->
                    <!--</template>-->
                <!--</el-form-item>-->
                <el-form-item>
                    <el-button type="primary" v-on:click="handleList" icon="el-icon-search">搜索</el-button>
                </el-form-item>
              <el-form-item style="float: right">
                <el-button type="primary" v-on:click="visible.addForm=true" icon="el-icon-circle-plus-outline">新增
                </el-button>
              </el-form-item>
              <el-form-item style="float: right">
                <el-button type="danger"  icon="el-icon-delete" @click="deleteBrands" :disabled="this.ids.length===0">删除
                </el-button>
              </el-form-item>
              <el-form-item style="float: right">
                <el-button type="success" v-on:click="handleRestFilters" icon="el-icon-refresh">重置</el-button>
              </el-form-item>

            </el-form>
        </el-col>
        <!--搜索end  -->

        <!--表格start -->
        <el-table :data="brands" :highlight-current-row="true" v-loading="visible.listLoading" style="width: 100%;"
                  @sort-change="handleSort" @selection-change="selectBrand">
            <el-table-column  type="selection" width="100px">
            </el-table-column>
            <el-table-column label="品牌logo" prop="brand_pic" width="200px">
                <template slot-scope="scope">
                    <a :href="scope.row.full_image" target="_blank"><img :src="scope.row.full_image"
                                                                         class="list-brand-image"/></a>
                </template>
            </el-table-column>
            <el-table-column prop="brand_name" label="品牌名称" width="200px">
            </el-table-column>
            <el-table-column prop="created_at" label="添加时间" sortable="custom" width="200px">
            </el-table-column>
            <el-table-column prop="product_num" label="商品数量" width="150px" max-length="50">

            </el-table-column>
            <el-table-column prop="brand_desc" label="品牌简介" :formatter="brandDescFormat">
            </el-table-column>

            <el-table-column label="操作" width="200px">
                <template slot-scope="scope">
                    <a @click="showEditForm(scope.$index, scope.row)">编辑</a>
                    <a @click="handleDelete(scope.$index, scope.row)">删除</a>
                </template>
            </el-table-column>
        </el-table>
        <!--表格end -->
        <!--分页start -->
        <el-col :span="24" class="toolbar">
            <el-pagination layout="total, sizes, prev, pager ,next" :page-size="filters.pageSize"
                           :total="pagination.total"
                           @current-change="handlePageChange" @size-change="handleSizeChange">
            </el-pagination>
        </el-col>
        <!--分页start -->

        <!--新增start -->
        <el-dialog title="新增品牌" :visible="visible.addForm" width="500px" :show-close="false">
            <div slot="title" class="dialog-title">
                新增品牌
            </div>

            <el-form :model="addForm" label-width="100px" ref="addForm" :rules="addFormRules">
                <el-form-item label="品牌名" prop="brand_name">
                    <el-input v-model="addForm.brand_name" auto-complete="off" :maxlength="20" width="20"
                              placeholder="品牌名称"></el-input>
                </el-form-item>
                <el-form-item label="关联分类" prop="category_ids">
                    <el-tree ref="addCategories"
                             :data="categoryList" :props="categoryProps" show-checkbox node-key="category_id"
                             :expand-on-click-node="false" class="categories">
                    </el-tree>
                </el-form-item>
                <el-form-item label="品牌说明" prop="brand_desc">
                    <el-input type="textarea" :rows="2" placeholder="请输入品牌描述" v-model="addForm.brand_desc" resize="none"
                              :maxlength=40>
                    </el-input>
                </el-form-item>
                <!--<el-form-item label="首字母" prop="brand_initial">-->
                    <!--<template>-->
                        <!--<el-select v-model="addForm.brand_initial" placeholder="请选择">-->
                            <!--<el-option-->
                                    <!--v-for="item in letterOption"-->
                                    <!--:key="item.value"-->
                                    <!--:label="item.label"-->
                                    <!--:value="item.value">-->
                            <!--</el-option>-->
                        <!--</el-select>-->
                    <!--</template>-->
                <!--</el-form-item>-->
                <el-form-item label="品牌图片" prop="brand_pic">
                    <el-upload :action="uploadUrl" :multiple="false" :on-success="onUploadSuccess"
                               list-type="picture-card"
                               ref="fileUpload" :showFileList="false" :headers="fileHeader" accept="jpg,png"
                               :before-upload="beforeUpload">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
                        <img :src="addBrandPic" class="upload-brand-img" v-show="addBrandPic"/>
                    </el-upload>

                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="addForm.sort" :min="1" :max="255"></el-input-number>
                </el-form-item>
                <!--<el-form-item label="推荐" prop="brand_recommend">-->
                    <!--<el-switch v-model="addForm.brand_recommend" inactive-value=1  active-value=0 ></el-switch>-->
                <!--</el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="hiddenAddForm">取消</el-button>
                <el-button type="primary" @click="handleAdd" :loading="visible.addLoading">提交</el-button>
            </div>
        </el-dialog>
        <!--新增end -->

        <!--编辑start -->
        <el-dialog title="编辑品牌" :visible="visible.editForm" width="500px" :show-close="false">

            <div slot="title" class="dialog-title">
                编辑品牌
            </div>

            <el-form :model="editForm" label-width="100px" ref="editForm" :rules="editFormRules">
                <el-form-item label="品牌名" prop="brand_name">
                    <el-input v-model="editForm.brand_name" auto-complete="off" :maxlength="20" width="20"></el-input>
                </el-form-item>
                <el-form-item label="关联分类" prop="category_ids">
                    <el-tree ref="editCategories" :data="categoryList" :props="categoryProps" show-checkbox
                             node-key="category_id" :expand-on-click-node="false" class="categories">
                    </el-tree>
                </el-form-item>
                <el-form-item label="品牌简介" prop="brand_desc">
                    <el-input type="textarea" :rows="2" placeholder="" v-model="editForm.brand_desc" :maxlength=40>
                    </el-input>
                </el-form-item>
                <!--<el-form-item label="首字母" prop="brand_initial">-->
                    <!--<template>-->
                        <!--<el-select v-model="editForm.brand_initial" placeholder="请选择">-->
                            <!--<el-option-->
                                    <!--v-for="item in letterOption"-->
                                    <!--:key="item.value"-->
                                    <!--:label="item.label"-->
                                    <!--:value="item.value">-->
                            <!--</el-option>-->
                        <!--</el-select>-->
                    <!--</template>-->
                <!--</el-form-item>-->
                <el-form-item label="品牌图片" prop="brand_pic">
                    <el-upload :action="uploadUrl" :multiple="false" :on-success="onEditUploadSuccess" ref="editUpload"
                               list-type="picture-card" :headers="fileHeader" accept="jpg,png" :showFileList="false"
                               :before-upload="beforeUpload">
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
                        <img :src="oldBrandPic" class="upload-brand-img" v-show="oldBrandPic"/>
                    </el-upload>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="editForm.sort" :min="1" :max="255"></el-input-number>
                </el-form-item>
                <!--<el-form-item label="推荐" prop="brand_recommend">-->
                    <!--<el-switch v-model="editForm.brand_recommend" :active-value="1" :inactive-value="0" actvie-text="是"-->
                               <!--inactvie-text="否"></el-switch>-->
                <!--</el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="hiddenEditForm">取消</el-button>
                <el-button type="primary" @click="handleEdit" :loading="visible.editLoading">提交</el-button>
            </div>
        </el-dialog>
        <!--编辑end -->
    </section>
</template>
<script>
  import {addBrand, getBrandList, uploadBrandUrl, editBrand, getCategories, deleteBrand} from '../../api/api';
  export default {
    data () {
      return {
        letterOption: [],
        fileList: [],
        //  火狐下需要指定返回的格式，不然默认返回xml
        fileHeader: {
          Authorization: `Bearer ${this.$store.state.token}`,
          Accept: 'application/json'
        },

        categoryProps: {
          label: 'category_name',
          children: 'children'
        },
        ids: [],
        brands: [],
        page: 1,
        uploadUrl: uploadBrandUrl,
        filters: {
          pageSize: 10,
          page: 1,
          brand_name: '',
          brand_initial: '',
          sort: '',
          expand: 'categories'
        },
        addBrandPic: '',
        pagination: {
          total: 0
        },
        visible: {
          addForm: false,
          addLoading: false,
          editForm: false,
          listLoading: false,
          editLoading: false
        },
        addForm: {
          brand_name: '',
//          brand_initial: '',
          brand_pic: '',
          sort: 1,
//          brand_recommend: 0,
          brand_desc: '',
          category_ids: []
        },
        editForm: {
          brand_name: '',
//          brand_initial: '',
          brand_pic: '',
          sort: 1,
          brand_id: '',
//          brand_recommend: 0,
          brand_desc: '',
          category_ids: []
        },
        assCategoryTitle: '',
        categoryList: [],
        categoryProp: {
          key: 'category_id',
          label: 'category_name'
        },
        assCategoryForm: {
          ids: [],
          brand_id: []
        },
        oldBrandPic: '',
        addFormRules: {
          brand_name: [
            {required: true, message: '请输入品牌名', trigger: 'blur'}
//            {pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '请输入合法的字符'}
          ],
          brand_initial: [
            {required: true, message: '请选择首字母', trigger: 'blur'}
          ],
          brand_pic: [
            {required: true, message: '请上传文件', trigger: 'blur'}
          ]
        },
        editFormRules: {
          brand_name: [
            {required: true, message: '请输入品牌名', trigger: 'blur'}
//            {pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '请输入合法的字符'}
          ],
          brand_initial: [
            {required: true, message: '请选择首字母', trigger: 'blur'}
          ]
        }
      };
    },
    methods: {
      //  格式化品牌简介
      brandDescFormat (row, column) {
        let desc = row.brand_desc
        if (desc.length > 30) {
          return desc.substr(0, 30) + '...'
        } else {
          return desc
        }
      },
      // 选择品牌
      selectBrand (rows) {
        this.ids = []
        for (let i of rows) {
          this.ids.push(i.brand_id)
        }
      },
      // 批量删除
      deleteBrands () {
        this.$confirm('确认删除选中品牌吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          // NProgress.start();
          let para = {}
          para.ids = this.ids
          addBrand(para).then((res) => {
            this.listLoading = false
            // NProgress.done();
            if (parseInt(res.status) === 1) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            } else {
              this.$alert('删除失败', '失败', {type: 'error'})
            }
            this.handleList()
          })
        }).catch(() => {
        })
      },
      // 删除
      handleDelete (index, row) {
        this.$confirm(`确认删除<${row.brand_name}>？`, '提示', {}).then(valid => {
          if (valid) {
            deleteBrand(row.brand_id).then(res => {
              if (parseInt(res.status) === 1) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.handleList();
              }
            });
          }
        }).catch(() => {
        })
      },
      // 表格索引
      getIndex (index) {
        return parseInt(this.filters.pageSize) * parseInt(this.filters.page - 1) + index + 1
      },
      // 获取分类列表
      handleCategories () {
        getCategories({category_level: 1}).then(res => {
          this.categoryList = res.data;
        })
      },
      // 新增
      handleAdd () {
        this.addForm.category_ids = this.$refs.addCategories.getCheckedKeys(true)
        this.$refs['addForm'].validate((valid) => {
          if (valid) {
            addBrand(this.addForm).then(res => {
              if (parseInt(res.status) === 1) {
                this.handleList();
                this.visible.addForm = false;
                this.addBrandPic = '';
                this.$refs['addForm'].resetFields();
                this.$message({
                  message: '新增成功',
                  type: 'success'
                });
              } else {
                this.$alert('新增失败', '错误', {type: 'error'});
              }
            });
          }
        });
      },
      // 编辑
      handleEdit () {
        this.editForm.category_ids = this.$refs.editCategories.getCheckedKeys(true)
        // 如果没有从新上传图片，则删除
        if (!this.editForm.brand_pic) {
          delete this.editForm.brand_pic;
        }
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            this.visible.editLoading = true;
            editBrand(this.editForm).then(res => {
              if (parseInt(res.status) === 1) {
                this.handleList();
                this.visible.editForm = false;
                this.visible.editImage = false;
                this.visible.oldImage = true;
                this.$refs['editUpload'].clearFiles();
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
              } else {
                this.$alert('修改失败', '错误', {type: 'error'});
              }
              this.visible.editLoading = false;
            });
          }
        });
      },
      // 显示新增表单
      hiddenAddForm () {
        this.addBrandPic = '';
        this.visible.addForm = false;
      },
      // 隐藏编辑表单
      hiddenEditForm () {
        this.visible.editForm = false;
      },

      // 显示编辑表单
      showEditForm (index, row) {
        this.visible.editForm = true;
        this.editForm = {
          brand_name: row.brand_name,
          brand_initial: row.brand_initial,
          brand_pic: '',
          sort: row.sort,
          brand_desc: row.brand_desc,
          brand_id: row.brand_id,
          brand_recommend: row.brand_recommend,
          category_ids: []
        };
        this.$nextTick(() => {
          this.$refs.editCategories.setCheckedNodes(row.categories);
        });
        this.oldBrandPic = row.full_image;
      },
      // 获取列表
      handleList () {
        this.visible.listLoading = true;
        getBrandList(this.filters).then(res => {
          if (parseInt(res.status) === 1) {
            this.brands = res.data;
            this.visible.listLoading = false;
            this.pagination.total = res.totalCount;
          }
        });
      },
      // 重置搜索列表
      handleRestFilters () {
        this.filters = {
          pageSize: 10,
          page: 1,
          brand_name: '',
          brand_initial: '',
          sort: ''
        }
        this.handleList();
      },
      // 服务器端排序
      handleSort (column) {
        if (column.order === 'descending') {
          this.filters.sort = '-' + column.prop;
        }
        if (column.order === 'ascending') {
          this.filters.sort = column.prop;
        }
        this.handleList();
      },
      // 页码改变
      handlePageChange (page) {
        this.filters.page = page;
        this.handleList();
      },
      // 分页条数改变
      handleSizeChange (size) {
        this.filters.pageSize = size;
        this.handleList();
      },

      // 上传文件验证
      beforeUpload (file) {
        if (file.size > 1024 * 1000) {
          this.$alert('图片大小必须小于1M', '错误', {type: 'error'})
          return false;
        }
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
          this.$alert('图片格式必须是PNG,JPG', '错误', {type: 'error'});
          return false;
        }
      },
      // 上传文件成功钩子
      onUploadSuccess (response) {
        if (parseInt(response.status) === 1) {
          this.addForm.brand_pic = response.data.path;
          this.addBrandPic = response.data.fullUrl;
          this.$refs.addForm.validateField('brand_pic');
        } else {
          this.$alert('服务器保存文件失败,请重新上传', '错误', {type: 'error'});
        }
      },
      // 编辑上传钩子
      onEditUploadSuccess (response) {
        if (parseInt(response.status) === 1) {
          this.editForm.brand_pic = response.data.path;
          this.oldBrandPic = response.data.fullUrl;
        } else {
          this.$alert('服务器保存文件失败,请重新上传', '错误', {type: 'error'});
        }
      }
    },
    mounted () {
      for (let i = 65; i < 91; i++) {
        let char = {
          value: String.fromCharCode(i),
          label: String.fromCharCode(i)
        };
        this.letterOption.push(char);
      }
      this.handleList();
      this.handleCategories();
    }
  };
</script>
<style rel="stylesheet/sass" lang="sass" scoped>
    a
        color: #62b8ff
        cursor: pointer
        margin-right: 20px
    .list-brand-image
        width: 100px
        height: 50px
        vertical-align: middle
        margin: 0 0
    .upload-brand-img
        position: absolute
        left: 0
        width: 148px
        height: 148px
        background-color: #fbfdff
        border: 1px dashed #c0ccda
        border-radius: 6px
    .categories
        border-radius: 6px
        border: 1px solid #c0ccda
        height: 160px
        overflow: auto
</style>
